<template>
  <div class="flow-chart" ref="flowchartdom"></div>
</template>

<script>
import * as echarts from "echarts";
import { kData } from "@/api/user";
export default {
  name: "FlowEcharts",
  components: {},
  data() {
    return {
      echartsData: [0, 1, 2, 3],
      charts: null,
    };
  },
  methods: {
    initCharts() {
      this.charts = echarts.init(this.$refs.flowchartdom);
      this.setOptionFun();
    },
    // 设置图标数据，生成图标
    setOptionFun() {
      const option = this.getOption();
      this.charts.setOption(option);
    },
    // 获取数据
    getOption() {
      const option = {
        title: {
          text: "",
        },
        tooltip: {
          trigger: "axis",
        },
        legend: {
          data: ["订单量", "点击量", "购买量", "退款量"],
          textStyle: {
            fontSize: 12, //字体大小
          },
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        toolbox: {
          feature: {
            saveAsImage: {},
          },
        },
        xAxis: {
          type: "category",
          boundaryGap: false,
          data: this.echartsData.x,
        },
        yAxis: {
          type: "value",
        },
        animationDuration: 300,
        animationDurationUpdate: 300,
        series: [
          {
            name: "订单量",
            type: "line",
            stack: "Total",
            data: this.echartsData.val[0],
          },
          {
            name: "点击量",
            type: "line",
            stack: "Total",
            data: this.echartsData.val[1],
          },
          {
            name: "购买量",
            type: "line",
            stack: "Total",
            data: this.echartsData.val[2],
          },
          {
            name: "退款量",
            type: "line",
            stack: "Total",
            data: this.echartsData.val[3],
          },
        ],
      };
      return option;
    },
    // 本函数 写 监听 container DOM 元素大小的改变
    watchContainerResize() {
      // 作用：监听 指定 DOM 元素 大小的改变
      this.observeContainer = new ResizeObserver(() => {
        this.charts.resize();
      });
      // console.log(this.$refs.flowchartdom);
      this.observeContainer.observe(this.$refs.flowchartdom);
    },
  },
  mounted() {
    kData().then((res) => {
      this.echartsData = res.data;
      // console.log(" this.echartsData.x", this.echartsData.x);
      this.initCharts();
      this.watchContainerResize();
    });
  },

  beforeDestroy() {
    this.charts.dispose();

    // 释放 ResizeObserver 监听的 DOM元素 对应的 内存
    this.observeContainer.unobserve(this.$refs.flowchartdom);
  },
};
</script>

<style scoped lang="scss">
.flow-chart {
  width: 100%;
  height: 100%;
}
</style>
